<template>
  <div class="article-list">
    <van-pull-refresh
    v-model="isRefrushLoading"
    @refresh="onRefresh"
    :success-text="successRefrushText"
    success-duration="1000"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <ArticleItem
        v-for="(article, index) in list"
        :article="article"
        :key="index"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/articles'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [], // 用于存放已经请求过的文章
      loading: false, // 加载中
      finished: false, // 没有更多
      timestamp: null, // 用于存放时间戳
      error: false, // 错误提示，请求失败点击重新加载
      isRefrushLoading: false, // 控制下拉刷新
      successRefrushText: ''
    }
  },
  methods: {
    // 当请求一次数据铺满整个屏幕时，或者资源全部加载完就停止加载，
    // 否则继续加载触发load
    async onLoad () {
      try {
        // 1.请求数据
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 0
        })
        // 2.将数据存在list数组
        const { results } = data.data
        this.list.push(...results)
        // 3.本次加载结束后，加载状态结束
        this.loading = false
        // 4.判断数据全部加载完成了吗
        if (results.length) { // 请求的数据是否还有内容
          // 有数据，则进行下一次加载,更新下次请求的时间戳（在响应数据中有上一次推荐时间）
          this.timestamp = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () { // 刷新
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 0
        })
        const { results } = data.data
        this.list.unshift(...results)
        this.successRefrushText = `刷新成功，更新了${results.length}条数据`
        this.isRefrushLoading = false
      } catch (err) {
        this.successRefrushText = '刷新失败，请稍后重试'
        this.isRefrushLoading = false
      }
    }
  }
}
</script>

<style scoped lang="less">
  .article-list {
    height: 79vh;
    overflow-y: auto;
  }
</style>
